package com.kyrioscraft.cloud.common.base;

import com.kyrioscraft.cloud.common.util.ParamValidator;
import com.kyrioscraft.cloud.common.vo.RestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
  * @author kyrioscraft
  * @date 2018/12/12 9:46
  *
  * @description //todo
  */
public class BaseController<Biz extends BaseBiz,Entity> {

    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected Biz baseBiz;


    @RequestMapping(value = "",method = RequestMethod.POST)
    @ResponseBody
    public RestResponse<Entity> add(@Valid @RequestBody Entity entity, BindingResult bindingResult){
        RestResponse restResponse = ParamValidator.checkParam(bindingResult);
        if (restResponse.getRet()){
            baseBiz.insertSelective(entity);
        }
        return restResponse;
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    @ResponseBody
    public RestResponse<Entity> get(@PathVariable int id){
        RestResponse<Entity> entityRestResponse = new RestResponse<>();
        Object o = baseBiz.selectById(id);
        entityRestResponse.data((Entity)o);
        return entityRestResponse;
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.PUT)
    @ResponseBody
    public RestResponse<Entity> update(@Valid @RequestBody Entity entity, BindingResult bindingResult){
        RestResponse restResponse = ParamValidator.checkParam(bindingResult);
        if (restResponse.getRet()){
            baseBiz.updateSelectiveById(entity);
        }
        return restResponse;
    }
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    public RestResponse<Entity> remove(@PathVariable int id){
        baseBiz.deleteById(id);
        return new RestResponse<Entity>();
    }

    @RequestMapping(value = "/all",method = RequestMethod.GET)
    @ResponseBody
    public List<Entity> all(){
        return baseBiz.selectListAll();
    }
}
